
package com.borqs.music.tasks;

import static com.borqs.music.http.RequestMethod.GET;
import static com.borqs.music.util.MusicConf.ReqType.MUSIC_DOWNLOAD;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.Map;

import android.os.Environment;

import com.borqs.music.executor.Task;
import com.borqs.music.executor.TaskListener;
import com.borqs.music.http.HttpRequest;
import com.borqs.music.http.HttpResponse;
import com.borqs.music.model.DownloadItem;
import com.borqs.music.util.AsyncLyricLoader;
import com.borqs.music.util.MusicConf;

public class DownloadSongTask extends Task {

    private static final String SDCARD_PATH = Environment.getExternalStorageDirectory().getPath();
    public static final String DOWNLOAD_DIR = new File(SDCARD_PATH, "borqs/borqsmusic/download/").getPath();
    
    private String mTicket;
    private DownloadItem mDownloadItem = null;
    private int mProgress = 0;

    public DownloadSongTask(TaskListener listener, String ticket, DownloadItem item) {
        super(listener);
        this.mTicket = ticket;
        this.mDownloadItem = item;
        File file = new File(DOWNLOAD_DIR);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    public DownloadItem getDownloadItem() {
        return mDownloadItem;
    }

    @Override
    public HttpRequest prepareRequest() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("songid", String.valueOf(mDownloadItem.getId()));
        
        String url = MusicConf.getUrl(MUSIC_DOWNLOAD);
        HttpRequest req = new HttpRequest(GET, url, mTicket, params);
        return req;
    }

    @Override
    public Object handleResponse(HttpResponse resp) throws Exception {
        // the value of Content-Length is negative sometimes.
        long max = Long.parseLong(resp.getResponseHeader("Content-Length"));
        String fileName = mDownloadItem.getFileName();

        File file = new File(DOWNLOAD_DIR, fileName + ".part");
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();
        try {
            InputStream is = resp.asStream();

            byte[] buf = new byte[1024 * 4];
            int size = 0;
            RandomAccessFile randFile;
            long downloadSize = 0;

            while ((size = is.read(buf)) != -1 && !isCanceled()) {
                randFile = new RandomAccessFile(file, "rw");
                randFile.seek(downloadSize);
                randFile.write(buf, 0, size);
                randFile.close();

                downloadSize += size;
                int currentPercent = (int) (100 * downloadSize / max);
                if (currentPercent > mProgress + 1) {
                    getListener().onProgress(this, downloadSize, max);
                    mProgress = currentPercent;
                }
            }

            is.close();

            if ((max > 0) && (downloadSize < max)) {
                // delete temporary file
                file.delete();
            } else {
                // Rename the file with correct suffix
                file.renameTo(new File(DOWNLOAD_DIR, fileName));
            }
        } finally {
            resp.disconnect();
        }
        return file;
    }
}
